#include "FilePaging.h"
#include <QDebug>
#include <QDir>


FilePaging::FilePaging(const QString &path, const int filesOfPage){
    setFilePath(path);
    setPagingRule(filesOfPage);
}

FilePaging::~FilePaging(){
    if(m_path){
        delete m_path;
        m_path = nullptr;
    }
}

void FilePaging::setFilePath(const QString &path){

    if(m_path){
        delete m_path;
        m_path = nullptr;
        m_files.clear();
    }

    m_path = new QDir(path);
    if(m_path){
        reLoad();
    }else{
        delete m_path;
        m_path = nullptr;
    }

}

void FilePaging::setPagingRule(const int filesOfPage){
    if(filesOfPage>0){
        m_filesOfPage = filesOfPage;
        m_currPageIndex = 0;
    }
}

void FilePaging::reLoad(){


    m_files.clear();
    if(!m_path->exists()){
       return;
    }
    m_currPageIndex = 0;
    m_path->setFilter(QDir::Files | QDir::NoDotAndDotDot);//不需要扫描子文件夹
    m_path->setSorting(QDir::Time); //时间排序是从最新到最早
    QStringList filters;
    filters << "*.jpg";
    m_path->setNameFilters(filters);
    auto files = m_path->entryList();


    for(auto &item:files){
        m_files.append(m_path->absoluteFilePath(item));
    }

}

bool FilePaging::nextPage(){
    return setCurrPage(m_currPageIndex+1);
}

bool FilePaging::prePage(){
    return setCurrPage(m_currPageIndex-1);
}

bool FilePaging::setCurrPage(int index){
    bool ret = index<pages() && index>=0;
    if(ret){
        m_currPageIndex = index;
    }
    return ret;
}

int FilePaging::getCurrPageIndex() const{
    return m_currPageIndex;
}

void FilePaging::getCurrPageFiles(QVector<QString> &files) const{
    files.clear();
    if(isEmpty())return;
    int pagevalue = m_currPageIndex*m_filesOfPage;
    int end = pagevalue+m_filesOfPage;
    for(int i = pagevalue;i<end&&i<m_files.length();++i){
        files.append(m_files.at(i));
    }
}

bool FilePaging::isEmpty()const{
    return m_files.isEmpty();
}

int FilePaging::pages()const{
    return  m_files.count()%m_filesOfPage
            ?m_files.count()/m_filesOfPage+1
           :m_files.count()/m_filesOfPage;
}

int FilePaging::count()const{
    return m_files.count();
}





